package org.erepublik.company.service;

import java.util.ArrayList;
import java.util.Arrays;

import org.erepublik.company.ECountry;
import org.erepublik.company.EProductType;
import org.erepublik.company.comparators.ProductComparatorByPriceInGold;
import org.erepublik.company.product.EProductAttribute;
import org.erepublik.company.product.ProductDesign;
import org.erepublik.company.product.Weapons;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONWeaponService extends JSONProductService<Weapons> implements IWeaponService {


    public JSONWeaponService(EProductType productType, String simpleName) {
        super(simpleName, productType);
    }
    
    @Override
    public String getMinutesSinceWeaponUpdate() {
        return getMinutesSinceUpdate();
    }

    @Override
    public Weapons[] getWeapons(ECountry country, ProductDesign design) {
        update();
        
        int dur = design.getAttributeValue(EProductAttribute.DURABILITY);
        int dmg = design.getAttributeValue(EProductAttribute.DAMAGE);
        
        
        if (country==null)
            return filter(dur, dmg, allProducts);
        return filter(dur, dmg, productMap.get(country));
    }

    @Override
    protected Weapons[] getEmptyTable() {
        return new Weapons[0];
    }

    @Override
    protected Weapons[] getProductFromJSONArray(JSONArray jsonArrayWithFood) throws JSONException {
        Weapons[] weapon = getWeaponsFromJSONArray(jsonArrayWithFood, productType).toArray(new Weapons[0]);
        Arrays.sort(weapon, new ProductComparatorByPriceInGold());
        return weapon;
    }
    
    public static ArrayList<Weapons> getWeaponsFromJSONArray(JSONArray jsonArrayWithFood, EProductType weaponType) throws JSONException {
        ArrayList<Weapons> weapon = new ArrayList<Weapons>();
        for (int i = 0; i < jsonArrayWithFood.length(); i++) {
            Weapons weap =  new Weapons(weaponType);
            Weapons.getWeaponsFromJSON( (JSONObject)jsonArrayWithFood.get(i), weap);
            weapon.add( weap );
        }

        return weapon;
    }   
    
    
    
    private Weapons[] filter(int minDur, int minDmg, Weapons[] weapons) {
        ArrayList<Weapons> newList = new ArrayList<Weapons>();
        for (Weapons weapon : weapons) {
            ProductDesign design = weapon.getProductDesign();
            int dur = design.getAttributeValue(EProductAttribute.DURABILITY);
            int dmg = design.getAttributeValue(EProductAttribute.DAMAGE);
            if (dur >= minDur && dmg >= minDmg)
                newList.add(weapon);
        }
        return newList.toArray(new Weapons[0]);
    }
    
    
    

}
